package com.xjl.user.controller;

import com.google.common.hash.BloomFilter;
import com.xjl.common.redis.config.RedisDistributedProperties;
import com.xjl.common.redis.utils.DistributedCache;
import com.xjl.common.redis.utils.StringRedisTemplateProxy;
import com.xjl.common.web.Res.Result;
import com.xjl.user.entity.po.UserPO;
import com.xjl.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
public class TestController {

    private final StringRedisTemplate stringRedisTemplate;
    private final StringRedisTemplateProxy stringRedisTemplateProxy;
    private final UserService userService;
    private final RedisDistributedProperties redisDistributedProperties;
    private final DistributedCache distributedCache;

    @GetMapping("test")
    public String test(){
        return "success";
    }

    @PostMapping("insert/user")
    public Result insertUser(@RequestBody UserPO userPO){
        try{
            boolean save = userService.save(userPO);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
        return Result.ok(userPO);
    }
    @PostMapping("remove/user")
    public Result removeUser(@RequestBody UserPO userPO){
        try{
            boolean remove = userService.removeById(userPO);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
        return Result.ok(userPO);
    }

    @PostMapping("test/cacheUtil")
    public Result testCacheUtil(@RequestBody UserPO userPO){
        UserPO userPO1 = stringRedisTemplateProxy.safeGet(redisDistributedProperties.getPrefix()+userPO.getUserName(), UserPO.class, () ->
                        userService.getById(userPO.getId())
                , 3000L, TimeUnit.DAYS);
        return Result.ok(userPO1);
    }

    @PostMapping("test/redis")
    public Result testRedis(@RequestBody UserPO userPO){
        stringRedisTemplate.opsForValue().set(userPO.getId().toString(),userPO.getUserName());
        return Result.ok(stringRedisTemplate.opsForValue().get(userPO.getId().toString()));
    }

    @PostMapping("test/redisCas")
    public Result testRedisCas(){
        Boolean aBoolean = distributedCache.CompareAndSweap("test_init_cache1", "test_init_cache", "test_init_cache_cas");

        return Result.ok(aBoolean);
    }
}
